package com.jr.controller;

import com.google.gson.Gson;
import com.jr.service.IBookInfoService;
import com.jr.service.impl.BookInfoServiceImpl;
import com.jr.util.PageHelper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@WebServlet("/binfo/*")
public class BookInfoController extends HttpServlet {

    IBookInfoService ibis = new BookInfoServiceImpl();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String requestURI = request.getRequestURI(); // 获取完整请求路径  --- /aaa/projectInfo/showdt
        int index = requestURI.lastIndexOf("/") + 1;
        String mName = requestURI.substring(index); // 截取最后一个"/"之后的字符串作为方法名

        /* 反射获取并调用对应方法 */
        Class cla = this.getClass(); // 获取当前类的Class对象
        Method method = null;
        try {
            // 查找当前类中是否存在指定名称、且参数为HttpServletRequest和HttpServletResponse的方法
            method = cla.getMethod(mName, HttpServletRequest.class, HttpServletResponse.class);

            response.setContentType("application/json;charset=UTF-8");
            request.setCharacterEncoding("UTF-8");

            // 调用找到的方法，this表示当前类实例，传递request和response作为参数
            method.invoke(this, request, response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace(); // 找不到对应方法的处理（这会导致404错误）
        } catch (IllegalAccessException e) {
            e.printStackTrace(); // 方法访问权限不足的处理
        } catch (InvocationTargetException e) {
            e.printStackTrace(); // 方法调用过程中抛出异常的处理
        }
    }

    public void getListByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PageHelper ph = new PageHelper();
        /*当前是第几页*/
        int indexpage = Integer.parseInt(request.getParameter("indexpage"));
        ph.setPageIndex(indexpage);
        ph.setDataCount(ibis.queryPageDataCount());
        ph.setListIndex(ibis.queryIndexData(ph));

        /*最终目的：*/
        response.getWriter().println(new Gson().toJson(ph));
    }


}
